package com.yonyou.brigade.third_parties.zteitc.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.order_center.model.CnvFlightOrderDO;
import com.yonyou.brigade.order_center.model.CnvHotelOrderDO;
import com.yonyou.brigade.order_center.model.CnvTrainOrderDO;
import com.yonyou.brigade.order_center.service.IBriFlightOrderService;
import com.yonyou.brigade.order_center.service.IBriHotelOrderService;
import com.yonyou.brigade.order_center.service.IBriTrainOrderService;
import com.yonyou.brigade.third_parties.zteitc.service.IZteitcOrderService;
import com.yonyou.brigade.third_parties.zteitc.service.IZteitcPublicService;
import com.yonyou.brigade.util.HttpClientUtil;
import com.yonyou.brigade.util.operateutil.DateUtils;
import com.yonyou.brigade.ybz.service.IConvertService;
import com.yonyou.ybzboot.starter.common.exception.BaseException;
import com.yonyou.ybzboot.starter.common.util.ResultUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * Created by Administrator on 2018/12/29.
 */
@RestController
@RequestMapping("/zteitc")
public class TestZteitcController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    @Qualifier("zteitcOrderServiceImpl")
    IZteitcOrderService zteitcOrderService;

    @Autowired
    IZteitcPublicService zteitcPublicService;


    @Autowired
    @Qualifier("briChannelServiceImpl")
    private IBriChannelService briChannelService;
    @Value("${cnv.baigade.system.code}")
    private String systemCode;
    @Value("${cnv.brigade.flight.tradetype}")
    private String flightTradetype;
    @Value("${cnv.brigade.hotel.tradetype}")
    private String hotelTradetype;
    @Value("${cnv.brigade.train.tradetype}")
    private String trainTradetype;
    @Value("${brigade.cur}")
    private String curEnv;
    private static final String DATEFORMAT = "yyyy-MM-dd";

    @Autowired
    @Qualifier("briFlightOrderServiceImpl")
    private IBriFlightOrderService briFlightOrderService;

    @Autowired
    @Qualifier("briHotelOrderServiceImpl")
    private IBriHotelOrderService briHotelOrderService;

    @Autowired
    @Qualifier("briTrainOrderServiceImpl")
    private IBriTrainOrderService briTrainOrderService;

    @Autowired
    @Qualifier("convertServiceImpl")
    private IConvertService convertService;


    @RequestMapping("/getFlightList")
    public String getFlightList(@RequestBody JSONObject parm) {
        if (parm != null && "135246".equals(parm.getString("token"))) {
            String begin = parm.get("begin").toString();
            String end = parm.get("end").toString();
            if (begin.equals("")) {
                //日期应精确到时分秒
                begin = DateUtils.getCurrentDateTimeMinusOneDay();
                end = DateUtils.getCurrentDateTime();
            }
            String tenant = "gztx1qwa";
            String orgpk = "0001A110000000001JVB";
            BriChannel briChannel = briChannelService.getEnableInfoByTenantOrg(tenant, orgpk, "zteitc");
            if (briChannel == null) {
                throw new BaseException(-100, "当前组织未开通中兴商旅");
            }
            int channelId = briChannel.getId();
            zteitcOrderService.getFlightOrderList(tenant, orgpk, channelId, begin, end);
        }
        return "结束";
    }

    @RequestMapping("/getHotel")
    public String getHotel(@RequestBody JSONObject parm) {
        if (parm != null && "135246".equals(parm.getString("token"))) {
            String begin = parm.get("begin").toString();
            String end = parm.get("end").toString();
            if (begin.equals("")) {
                //日期应精确到时分秒
                begin = DateUtils.getCurrentDateTimeMinusOneDay();
                end = DateUtils.getCurrentDateTime();
            }
            String tenant = "gztx1qwa";
            String orgpk = "0001A110000000001JVB";
            BriChannel briChannel = briChannelService.getEnableInfoByTenantOrg(tenant, orgpk, "zteitc");
            if (briChannel == null) {
                throw new BaseException(-100, "当前组织未开通中兴商旅");
            }
            int channelId = briChannel.getId();
            zteitcOrderService.getHotelOrderList(tenant, orgpk, channelId, begin, end);

        }
        return "结束";
    }

    @RequestMapping("/getTrain")
    public String getTrain(@RequestBody JSONObject parm) {
        if (parm != null && "135246".equals(parm.getString("token"))) {
            String begin = parm.get("begin").toString();
            String end = parm.get("end").toString();
            if (begin.equals("")) {
                //日期应精确到时分秒
                begin = DateUtils.getCurrentDateTimeMinusOneDay();
                end = DateUtils.getCurrentDateTime();
            }
            String tenant = "gztx1qwa";
            String orgpk = "0001A110000000001JVB";
            BriChannel briChannel = briChannelService.getEnableInfoByTenantOrg(tenant, orgpk, "zteitc");
            if (briChannel == null) {
                throw new BaseException(-100, "当前组织未开通中兴商旅");
            }
            int channelId = briChannel.getId();
            zteitcOrderService.getTrainOrderList(tenant, orgpk, channelId, begin, end);
        }
        return "结束";
    }

    @RequestMapping("/noteFlight")
    public void noteFlight(@RequestBody JSONObject parm) {
        if (parm != null && "135246".equals(parm.getString("token"))) {
            List<BriChannel> briChannels = briChannelService.getDistinctEnableChannelGroupByTenant();
            if (briChannels != null && briChannels.size() > 0) {
                for (BriChannel briChannel : briChannels) {
                    if (!briChannel.getTenant().equals("gztx1qwa")) {
                        continue;
                    }
                    Map<String, String> flightParams = new HashMap<>();
                    // 按租户以及国内、正常单查询并推送
                    flightParams.put("tenant", briChannel.getTenant());
                    flightParams.put("is_domc", "D");
                    // staus_type 和 order_type 均为正常单-退票单 但是 status_type 为空
                    flightParams.put("order_type", "N");
                    flightParams.put("order_status", "NP");
                    SimpleDateFormat sf = new SimpleDateFormat(DATEFORMAT);
                    Date yesterday = null;
                    try {
                        yesterday = sf.parse(DateUtils.getCurrentDateMinusOneDay(DATEFORMAT));
                    } catch (ParseException e) {
                        logger.error("日期转换错误！" + e.getMessage());
                    }
                    List<CnvFlightOrderDO> flightOrderDOs = briFlightOrderService.getCnvFlightOrderDos(flightParams, yesterday, yesterday);
                    for (CnvFlightOrderDO flightOrderDO : flightOrderDOs) {
                        if (!StringUtils.isEmpty(flightOrderDO.getUserId())) {
                            push(flightOrderDO.getUserId(), flightOrderDO.getTenant(), flightTradetype, JSON.parseObject(JSON.toJSONStringWithDateFormat(flightOrderDO, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat)));
                        }
                    }
                }
            }
        }

    }

    @RequestMapping("/noteTrain")
    public void noteTrain(@RequestBody JSONObject parm) {
        if (parm != null && "135246".equals(parm.getString("token"))) {
            List<BriChannel> briChannels = briChannelService.getDistinctEnableChannelGroupByTenant();
            if (briChannels != null && briChannels.size() > 0) {
                for (BriChannel briChannel : briChannels) {
//                if(!briChannel.getTenant().equals("gztx1qwa"))continue;
                    Map<String, String> trainParams = new HashMap<>();
                    trainParams.put("tenant", briChannel.getTenant());
                    trainParams.put("order_status", "TP");
                    trainParams.put("status_type", "N");
                    SimpleDateFormat sf = new SimpleDateFormat(DATEFORMAT);
                    Date yesterday = null;
                    try {
//                    yesterday = sf.parse(DateUtils.getCurrentDateMinusOneDay(DATEFORMAT));
                        yesterday = sf.parse("2018-11-14");
                    } catch (ParseException e) {
                        logger.error("日期转换错误！" + e.getMessage());
                    }
//                List<CnvFlightOrderDO> flightOrderDOs = briFlightOrderService.getCnvFlightOrderDos(flightParams, yesterday, yesterday);
                    List<CnvTrainOrderDO> trainOrderDOs = briTrainOrderService.getCnvTrainOrderDos(trainParams, yesterday, yesterday);
                    for (CnvTrainOrderDO cnvTrainOrderDO : trainOrderDOs) {
                        if (!StringUtils.isEmpty(cnvTrainOrderDO.getUserId())) {
                            push(cnvTrainOrderDO.getUserId(), cnvTrainOrderDO.getTenant(), trainTradetype, JSON.parseObject(JSON.toJSONStringWithDateFormat(cnvTrainOrderDO, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat)));
                        }

                    }

                }
            }
        }
    }

    @RequestMapping("/noteHotel")
    public void noteHotel(@RequestBody JSONObject parm) {
        if (parm != null && "135246".equals(parm.getString("token"))) {
            List<BriChannel> briChannels = briChannelService.getDistinctEnableChannelGroupByTenant();
            if (briChannels != null && briChannels.size() > 0) {
                for (BriChannel briChannel : briChannels) {
                    if (!briChannel.getTenant().equals("gztx1qwa")) {
                        continue;
                    }
                    SimpleDateFormat sf = new SimpleDateFormat(DATEFORMAT);
                    Date yesterday = null;
                    try {
                        yesterday = sf.parse(DateUtils.getCurrentDateMinusOneDay(DATEFORMAT));
                    } catch (ParseException e) {
                        logger.error("日期转换错误！" + e.getMessage());
                    }
                    Map<String, String> hotelParams = new HashMap<>();
                    hotelParams.put("tenant", briChannel.getTenant());
                    hotelParams.put("is_domc", "D");
                    List<CnvHotelOrderDO> hotelOrderDOS = briHotelOrderService.getCnvHotelOrderDos(hotelParams, yesterday, yesterday);
                    for (CnvHotelOrderDO hotelOrderDO : hotelOrderDOS) {
                        if (!StringUtils.isEmpty(hotelOrderDO.getUserId())) {
                            push(hotelOrderDO.getUserId(), hotelOrderDO.getTenant(), hotelTradetype, JSON.parseObject(JSON.toJSONStringWithDateFormat(hotelOrderDO, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat)));
                        }
                    }
                }
            }
        }

    }


    private void push(String userId, String tenant, String tradeType, JSONObject jsonObject) {
        /**
         * 1.HTTPCLIENT请求转换平台转换数据
         * 2.组装参数
         * 3.调用报账服务dubbo保存记事
         */
        //tenant = "zrez2bx9";
        JSONObject cnvFlightOrder = convertService.convert(tradeType, systemCode, userId, tenant, null, jsonObject);
        Map<String, List<Map<String, Object>>> noteMap = new HashMap<>();
        List<Map<String, Object>> noteList = new ArrayList<>();
        if (cnvFlightOrder.getBoolean("success")) {
            JSONArray noteJsonArray = cnvFlightOrder.getJSONArray("result");
            for (int i = 0; i < noteJsonArray.size(); i++) {
                JSONObject data = noteJsonArray.getJSONObject(i).getJSONObject("data");
                data.put("orderId", jsonObject.getString("id"));
                noteList.add(data);
                noteMap.put(noteJsonArray.getJSONObject(i).getString("desbilltypecode"), noteList);
//                convertService.pushToYBZ(noteMap, userId, tenant,tradeType,jsonObject.getString("id"));
            }

        } else {
            // 为了对在数据转换中出现错误的数据在推送服务中进行错误处理以及提醒
//            convertService.pushToYBZ(noteMap, userId, tenant,tradeType,jsonObject.getString("id"));
        }
    }

    /**
     * 获取中兴结算信息
     *
     * @param param periodName：结算周期，tenant：租户，orgpk：组织PK
     * @return
     */
    @RequestMapping("/getStatement")
    public JSONArray getStatement(@RequestBody JSONObject param) {
        String periodName = param.getString("periodName");
        String tenant = param.getString("tenant");
        String orgpk = param.getString("orgpk");
        return zteitcPublicService.findStatements(tenant, orgpk, periodName);
    }

    /**
     * 查询结算单订单明细
     *
     * @param param billNum：结算单号，tenant：租户，orgpk：组织PK
     * @return
     */
    @RequestMapping("/getStatementDetail")
    public JSONArray getStatementDetail(@RequestBody JSONObject param) {
        String billNum = param.getString("billNum");
        String tenant = param.getString("tenant");
        String orgpk = param.getString("orgpk");
        return zteitcPublicService.findStatementsDetail(tenant, orgpk, billNum);
    }

//    /**
//     * 批量同步一级部门
//     *
//     * @param param
//     * @return
//     */
//    @RequestMapping("/syncDepatement")
//    public Object syncDepatement(@RequestBody JSONObject param) {
//        String tenant = param.getString("tenant");
//        String pkOrg = param.getString("pkOrg");
//        BriChannel briChannel = briChannelService.getEnableInfoByTenantOrg(tenant, pkOrg, "zteitc");
//        if (briChannel == null) {
//            return "未开通商旅";
//        }
//        return zteitcPublicService.syncDepatement(briChannel,param);
//    }

}